package client

import (
	"fmt"
	"gitee.com/alex_li/amazon-rpt/internal/db"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/app-starter/persistence"
	"github.com/lishimeng/app-starter/server"
	"github.com/lishimeng/go-log"
	"net/http"
)

type CreateReq struct {
	ClientId string `json:"clientId,omitempty"`
	Secret   string `json:"secret,omitempty"`
}

func newClient(ctx server.Context) {
	var err error
	var req CreateReq
	var resp app.Response

	err = ctx.C.ReadJSON(&req)
	if err != nil {
		log.Info(err)
		resp.Code = http.StatusBadRequest
		ctx.Json(resp)
		return
	}
	err = app.GetOrm().Transaction(func(tx persistence.TxContext) (e error) {
		var list []db.AmazonLwa
		_, e = tx.Context.QueryTable(new(db.AmazonLwa)).
			Filter("ClientId", req.ClientId).
			Limit(1).All(&list)
		if e != nil {
			log.Info(e)
			return
		}
		if len(list) > 0 {
			e = fmt.Errorf("client_id exist: %s", req.ClientId)
			return
		}
		var ins db.AmazonLwa
		ins.ClientId = req.ClientId
		ins.Secret = req.Secret
		ins.Status = 10
		_, e = tx.Context.Insert(&ins)
		return nil
	})
	if err != nil {
		log.Info(err)
		resp.Code = http.StatusBadRequest
		ctx.Json(resp)
		return
	}
	resp.Code = http.StatusOK
	ctx.Json(resp)
}
